const mongoose = require("../db");
const Schema = mongoose.Schema;

const reviewSchema = new Schema({
  reviewid: { type: String, required: true, unique: true },
  orderid: { type: String, required: true },
  userid: { type: String, required: true },
  rating: { 
    type: Number, 
    required: true,
    min: 1,
    max: 5
  },
  content: { type: String, default: '' },
  created_at: { type: Date, default: Date.now },
  updated_at: { type: Date, default: Date.now }
});

// 创建复合索引
reviewSchema.index({ orderid: 1, userid: 1 }, { unique: true }); // 确保一个订单一个用户只能评价一次
reviewSchema.index({ userid: 1, created_at: -1 }); // 用户评价列表查询优化
reviewSchema.index({ rating: 1 }); // 按评分筛选优化
reviewSchema.index({ created_at: -1 }); // 按时间排序优化

// 更新时间中间件
reviewSchema.pre('save', function(next) {
  this.updated_at = Date.now();
  next();
});

reviewSchema.pre('findOneAndUpdate', function(next) {
  this.set({ updated_at: Date.now() });
  next();
});

module.exports = mongoose.model("Review", reviewSchema);